package com.parenting.controller;



import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.parenting.entities.SystemUserDO;
import com.parenting.enums.ResultEnum;
import com.parenting.feign.controller.IFeignSystemShopController;
import com.parenting.feign.entities.ParentingShopDTO;
import com.parenting.model.IMPage;
import com.parenting.oauth2.config.AuthUtil;
import com.parenting.request.*;
import com.parenting.request.wechat.PhoneCodeRequest;
import com.parenting.response.AppletClerkDetailsResponse;
import com.parenting.response.AppletShopUserListResponse;
import com.parenting.service.SystemUserService;
import com.parenting.util.TXSendSms;
import com.parenting.util.base.Result;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "我的", description = "提供（安全中心、门店详情、店员管理、设置）")
@RequestMapping("/my")
public class MySettingsController {

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private IFeignSystemShopController iFeignSystemShopController;

    @ApiOperation("查询当前登录人员店铺详情")
    @GetMapping("shop")
    public Result<ParentingShopDTO> getShopByShopId(){
        ParentingShopDTO shopByShopId = iFeignSystemShopController.getShopByShopsId(AuthUtil.getUserInfo().getShopId());
        return  Result.buildSuccess(shopByShopId);
    }





    /**
     * 修改密码
     * @param req
     * @return
     */
    @ApiOperation("密码设置")
    @PostMapping("updatePws")
    public Result updatePassword(@RequestBody UpdateLoginUserPasswordRequest req){

        return   systemUserService.updateLoginUserPassword(req,AuthUtil.getUserInfo().getId());
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /****
     * 设置提现密码
     * @param extractPasswordRequest
     * @return
     */
    @ApiOperation("设置提现密码")
    @PostMapping("saveEPws")
    public Result saveExtractPassword(@RequestBody @Validated AddExtractPasswordRequest extractPasswordRequest){
        String s = stringRedisTemplate.opsForValue().get("user:phone:" + extractPasswordRequest.getPhone());
        if (!extractPasswordRequest.getCode().equals(s)){
            return Result.buildError(ResultEnum.CODE_ERROR.getMessage());
        }
        return  systemUserService.saveExtractPassword(extractPasswordRequest,AuthUtil.getUserInfo().getId());
    }


    @ApiOperation("提现密码发送验证码")
    @PostMapping("password/code/{phone}")
    public  Result registerUser(@PathVariable("phone") String phone){
        String[] phones = {"+86 "+phone};
        String newCode= TXSendSms.getNewcode();
        stringRedisTemplate.opsForValue().set("user:phone:"+phone,newCode,60, TimeUnit.SECONDS);
        String[] code = {newCode};
        try {
            TXSendSms.sendSms("AKIDOMMbJaiLFwiwueDVcU1kALI0Z9zbjzSn", "LITvFKBoCL0ed9P4dEuQkgOxAAlT5RaV",
                    "1400488934", "威海优珍", "879807", phones, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return  Result.buildSuccess();
    }
    /***
     * 个人设置
     * @param request
     * @return
     */
    @ApiOperation("个人设置")
    @PostMapping("settings")
    public Result updatePersonalSettings(@RequestBody ShopUserUpdateRequest request){
        request.setId(AuthUtil.getUserInfo().getId());
        systemUserService.updateUser(request);
        return  Result.buildSuccess();
    }


    @ApiOperation("店员列表")
    @PostMapping("shop/list")
    public Result<IMPage<AppletShopUserListResponse>> getShopUserList(@RequestBody AppletShopUserListRequest request){
        IMPage<AppletShopUserListResponse> shopUserList = systemUserService.getShopUserList(AuthUtil.getUserInfo().getShopId(), request);
        return  Result.buildSuccess(shopUserList);
    }

    @ApiOperation("店员详情")
    @GetMapping("{userId}")
    public Result<AppletClerkDetailsResponse> getUserByUserId(@PathVariable("userId") String userId){
        SystemUserDO byId = systemUserService.getById(userId);


        return Result.buildSuccess(BeanUtil.copyProperties(byId,AppletClerkDetailsResponse.class));

    }

    @ApiOperation("店员修改")
    @PutMapping
    public Result<AppletClerkDetailsResponse> updateUserByUserId(@RequestBody ShopUserUpdateRequest request){
        systemUserService.updateUser(request);
        return Result.buildSuccess();

    }


    @ApiOperation("获得要修改手机获得验证码")
    @PostMapping("phone/code/")
    public  Result odlPCode(){
        String[] phones = {"+86 "+AuthUtil.getUserInfo().getMobile()};
        String newCode= TXSendSms.getNewcode();
        stringRedisTemplate.opsForValue().set("user:phone:"+AuthUtil.getUserInfo().getMobile(),newCode,60, TimeUnit.SECONDS);
        String[] code = {newCode};
        try {
            TXSendSms.sendSms("AKIDOMMbJaiLFwiwueDVcU1kALI0Z9zbjzSn", "LITvFKBoCL0ed9P4dEuQkgOxAAlT5RaV",
                    "1400488934", "威海优珍", "879807", phones, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return  Result.buildSuccess(code);
    }

    @ApiOperation("校验更换手机的验证码是否正确")
    @PostMapping("phone/code/{code}")
    public  Result chekPhoneCode(@PathVariable("code") String code){
        String s = stringRedisTemplate.opsForValue().get("user:phone:" + AuthUtil.getUserInfo().getMobile());
        if (code.equals(s)) {
             return  Result.buildSuccess();
        }else{
            return Result.buildError("验证码错误！");
        }

    }



    @ApiOperation("获得新手机获得验证码")
    @PostMapping("new/phone/{phone}")
    public  Result newCode(@PathVariable("phone") String phone){
        String[] phones = {"+86 "+phone};
        String newCode= TXSendSms.getNewcode();
        stringRedisTemplate.opsForValue().set("user:phone:"+phone,newCode,60, TimeUnit.SECONDS);
        String[] code = {newCode};
        try {
            TXSendSms.sendSms("AKIDOMMbJaiLFwiwueDVcU1kALI0Z9zbjzSn", "LITvFKBoCL0ed9P4dEuQkgOxAAlT5RaV",
                    "1400488934", "威海优珍", "879807", phones, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return  Result.buildSuccess(code);
    }

    @ApiOperation("修改新手机号")
    @PostMapping("/update/phone/")
    public  Result updatePhone(@RequestBody @Validated  PhoneCodeRequest request){
        String s = stringRedisTemplate.opsForValue().get("user:phone:" +request.getPhone());
        if (request.getCode().equals(s)){
            LambdaUpdateWrapper<SystemUserDO> wrapper=new LambdaUpdateWrapper();
            wrapper.eq(SystemUserDO::getId,AuthUtil.getUserInfo().getId());
            wrapper.set(SystemUserDO::getMobile,request.getPhone());
            systemUserService.update(wrapper);
            return  Result.buildSuccess();
        }
        return Result.buildError("验证码错误！");
    }

}
